#!/bin/bash

trapFunction () {
  echo Exiting
}

read -p "Do you want to retrieve json from data.sa.gov before transforming -'Y' for yes ('N' will transform only)?  " choice
echo    # (optional) move to a new line
if [[ $choice =~ ^[Yy]$ ]]
then
  echo Retrieving json from data.sa.gov
  rm /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/JsonXML/*
  python /home/anucsiro/workspace/XML/ShellScripts/CKAN_API3_JsonToXML.py --identifierListURI http://data.sa.gov.au/api/3/action/package_list --descriptionByIdentifierURI "http://data.sa.gov.au/api/3/action/package_show?id=%s" --outputDirectory ForDataSaGovAu
fi

rm /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/*

rm /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/DataSaGovRegistryObjects.xml
echo '<registryObjects xmlns:xs="http://www.w3.org/2001/XMLSchema"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xmlns="http://ands.org.au/standards/rif-cs/registryObjects"
                 xsi:schemaLocation="http://ands.org.au/standards/rif-cs/registryObjects http://services.ands.org.au/documentation/rifcs/schema/registryObjects.xsd">' >> /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/DataSaGovRegistryObjects.xml


trap trapFunction EXIT
trap 'exit 127' INT

ls "/home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/JsonXML" | while read f; do
    fileNamePath="/home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/JsonXML/""$f"
    fileNameNoExtension=${f%.*}
    echo File: $fileNamePath
    echo Transforming $fileNamePath
    echo java -jar /home/anucsiro/workspace/XML/XSLT/saxon9he.jar "/home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/JsonXML/""$f" /home/anucsiro/workspace/XML/XSLT/json_To_RIFCS/data.sa.gov.au/data.sa.gov.au_json_to_rif-cs.xsl > /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    java -jar /home/anucsiro/workspace/XML/XSLT/saxon9he.jar \
        "/home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/JsonXML/""$f" \
        /home/anucsiro/workspace/XML/XSLT/json_To_RIFCS/data.sa.gov.au/data.sa.gov.au_json_to_rif-cs.xsl \
        > /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/$fileNameNoExtension"_rif-cs.xml" 
    echo XML written to /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/$fileNameNoExtension"_rif-cs.xml"

    cat /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/$fileNameNoExtension"_rif-cs.xml" >> /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/DataSaGovRegistryObjects.xml
   
done

 echo '</registryObjects>' >> /home/anucsiro/workspace/XML/ShellScripts/ForDataSaGovAu/RifCs/DataSaGovRegistryObjects.xml











